<?php

class Users_Model extends MY_Model {

	public function __construct() {
		$this -> load -> database();
	}

	// get
	public function gets($id = false) {
		if ($id == false) {
			$query = $this -> db -> get($this -> table);
			return $query -> result_array();
		} else {
			$this -> db -> where($this -> primary_key, $id);
			$q = $this -> db -> get($this -> table);
			$data = $q -> result_array();
			return $data;
		}
	}

	public function getById($user_id) {
		$this -> db -> where($this -> primary_key, $user_id);
		$q = $this -> db -> get($this -> table);
		$data = $q -> result_array();
		return $data;

	}

	public function getAll() {
		$this -> db -> where('delete_flag', 0);
		$query = $this -> db -> get($this -> table);
		return $query -> result_array();
	}

	// insert
	function insert($data = array()) {
		$data_insert = array('first_name' => $data['firstName'], 'last_name' =>$data['lastName'], 'user_name' =>$data['userName'], 'password' => md5($data['password']), 'city' => $data['city'], 'state' => $data['state'], 'company' => $data['company'], 'update_date' => time());
		$result = $this -> db -> insert('user', $data_insert);
		$insert_id = mysql_insert_id();
		if ($result) {
			$id = $this -> db -> insert_id();
			//$data_update = array('unlock_code' => md5($id . $data['unlock_code']), );
			//$this -> db -> where($this -> primary_key, $id);
			//$this -> db -> update('users', $data_update);
			//echo $insert_id;
			return $insert_id;
			
		} else
			return 0;
	}


	//update
	function update($id, $data = array()) {
		//get old data
		$u = $this -> gets($id);
		//if(!isset($data['username'])) $data['username'] = $u['username'];
		//if(!isset($data['password'])) $data['password'] = $u['password'];
		if (!isset($data['fullname']))
			$data['fullname'] = $u['fullname'];
		if (!isset($data['image']))
			$data['image'] = $u['image'];
		if (!isset($data['role']))
			$data['role'] = $u['role'];
		if(isset($data['phone']))
		$data_update = array('phone' => $data['phone'], 'address' => $data['address'], 'fullname' => $data['fullname'], 'image' => $data['image'], 'role' => $data['role']);
		$this -> db -> where($this -> primary_key, $id);
		if ($this -> db -> update('users', $data_update))
			return true;
		else
			return false;
	}

	function isExistUsername($username) {

		$this -> db -> where('username', $username);
		$q = $this -> db -> get($this -> table);
		$data = $q -> result_array();
		//print_r($data);
		if (count($data) > 0)
			return true;
		else
			return false;
	}

	function isExistUserId($id) {
		$this -> db -> where('user_id', $id);
		$q = $this -> db -> get($this -> table);
		$data = $q -> result_array();
		//print_r($data);
		if (count($data) > 0) {
			return 1;
		} else {
			return 0;
		}

	}

	function saveImage($user_id, $image_path) {

		$this -> db -> where($this -> primary_key, $user_id);
		if ($this -> db -> update('users', array('image' => $image_path)))
			return true;
		else
			return false;
	}

}
